<script setup>
import { ref } from "vue" 

const chatList = ref([])


const msg = ref("")
 // 创建 WebSocket 连接
const socket = new WebSocket('ws://localhost:3000');

// 连接成功后处理
socket.onopen = () => {
  console.log('WebSocket 连接已建立');
};

// 监听消息
socket.onmessage = (event) => {
  // msg.value = event.data
  const chat = {
    from:false,
    msg:event.data
  }
  chatList.value.push(chat)
  console.log('收到服务器消息:', event.data);
};

// 监听连接关闭
socket.onclose = () => {
  console.log('WebSocket 连接已关闭');
};

// 监听错误
socket.onerror = (error) => {
  console.error('WebSocket 错误:', error);
};

// 发送消息的功能
const send = () => {
  const message = msg.value;
  console.log('发送消息:', message);
  socket.send(message);
  chatList.value.push({
    from:true,
    msg:msg.value
  })
};
</script>

<template>
    <div>
<button @click="send">send</button>
<input v-model="msg" type="text">
<!-- {{ msg }} -->
<div v-for="(item, index) in chatList" :key="index">
  <div class="me" v-if="item.from">{{ item.msg }}</div>
  <div class="other" v-else>{{ item.msg }}</div>

</div>
    </div>
</template>

<style scoped>
.me{
  color: green;
}
.other{
  color: pink;
}

</style>